<template>
  <section class="flex flex-col h-full">
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="97px"
    >
      <el-form-item prop="orderPeriod" style="width: 500px">
        <el-select
          v-model="searchNameVal"
          placeholder="请选择时间类型"
          style="width: 120px; height: 36px"
        >
          <el-option
            v-for="dict in timetypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <el-date-picker
          v-model="orderPeriod"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[
            new Date('1 00:00:00'),
            new Date('1 23:59:59')
          ]"
          class="form-item-height"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" type="primary">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['salesWaybill:export']"
        >
          <Icon icon="ep:download" class="mr-5px" />
          导出
        </el-button>
      </el-form-item>
    </el-form>
    <el-tabs
      v-model="queryParams.segmentedDeviceCode"
      type="card"
      @tab-change="tabChange"
    >
      <el-tab-pane
        v-for="item in tabs"
        :key="item.value"
        :label="item.label + '（' + item.num + '）'"
        :name="item.value"
      >
      </el-tab-pane>
    </el-tabs>
    <!--    <div class="flex justify-end mb-16px">-->
    <!--      <div>-->
    <!--        <el-button @click="toggle">-->
    <!--          <el-tooltip effect="dark" content="全屏" placement="top-start">-->
    <!--            <div style="width: 22px;height: 22px;">-->
    <!--              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">-->
    <!--                <path d="M8 3V5H4V9H2V3H8ZM2 21V15H4V19H8V21H2ZM22 21H16V19H20V15H22V21ZM22 9H20V5H16V3H22V9Z"></path>-->
    <!--              </svg>-->
    <!--            </div>-->
    <!--          </el-tooltip>-->
    <!--        </el-button>-->
    <!--        <CustomTool :menuType="'salesWaybillManage'" @columnsChange="getCustomColumns()"></CustomTool>-->
    <!--      </div>-->
    <!--    </div>-->
    <custom-table
      ref="singleTableRef"
      class="flex-1"
      :loading="loading"
      :columns="columns"
      :dataSource="list"
      :height="'100%'"
      :showSummary="true"
      :get-summaries="handleSummaries"
    >
      <template #index="{ row }">
        {{ row.index }}
      </template>
      <template #tenantName_filter>
        <custom-form
          v-model="searchParams.enterId"
          :type="'select'"
          :options="tenantList"
          @filterChange="filterChange()"
        ></custom-form>
      </template>
      <template #tenantName="{ row }">
        <el-tooltip
          class="box-item"
          effect="dark"
          :content="row.tenantName"
          placement="top-start"
        >
        </el-tooltip>
      </template>
      <template #waybillNo_filter>
        <custom-form
          v-model="searchParams.waybillNo"
          :type="'input'"
          :maxlength="50"
          @filterChange="filterChange()"
        ></custom-form>
      </template>
      <template #waybillNo="{ row }">
        <span
          class="cursor-pointer highlight-title"
          style="color: #2893ff; cursor: pointer"
          @click="openDetailModel(row.id)"
          >{{ row.waybillNo }}</span
        >
      </template>
      <template #customerName_filter>
        <custom-form
          v-model="searchParams.customerName"
          :type="'input'"
          :maxlength="50"
          @filterChange="filterChange()"
        ></custom-form>
      </template>
      <template #productName_filter>
        <custom-form
          v-model="searchParams.productName"
          :type="'input'"
          :maxlength="50"
          @filterChange="filterChange()"
        ></custom-form>
      </template>
      <template #waybillStatus_filter>
        <custom-form
          v-model="searchParams.waybillStatus"
          :type="'select'"
          :options="waybillstatusList"
          @filterChange="filterChange()"
        ></custom-form>
      </template>
      <template #waybillStatus="{ row }">
        <dict-tag
          :type="DICT_TYPE.SALE_WAYBILL_STATUS"
          :value="row.waybillStatus"
          :class="{
            'no-back-style': true,
            'sh-type': row.waybillStatus == 0,
            'rc-type': row.waybillStatus == 1,
            'lp-type': row.waybillStatus == 2,
            'zm-type': row.waybillStatus == 3,
            'cm-type': row.waybillStatus == 4,
            'cc-type': row.waybillStatus == 5,
            'wc-type': row.waybillStatus == 6,
            'zf-type': row.waybillStatus == 7,
            'zz-type': row.waybillStatus == 8
          }"
        />
      </template>
      <template #vehicleNo_filter>
        <custom-form
          v-model="searchParams.vehicleNo"
          :type="'input'"
          :maxlength="8"
          @filterChange="filterChange()"
        ></custom-form>
      </template>
      <template #loadingSiteName_filter>
        <custom-form
          v-model="searchParams.loadingPlaceName"
          :type="'input'"
          :maxlength="50"
          @filterChange="filterChange()"
        ></custom-form>
      </template>
      <template #unLoadingSiteName_filter>
        <custom-form
          v-model="searchParams.unloadingPlaceName"
          :type="'input'"
          :maxlength="50"
          @filterChange="filterChange()"
        ></custom-form>
      </template>
      <template #goodsPaymentMark="{ row }">
        <StatusText
          v-if="
            ![null, undefined].includes(
              row.goodsPaymentMark
            )
          "
          class="status-text"
          :type="DICT_TYPE.GOODS_PAYMENT_MARK"
          :value="row.goodsPaymentMark"
        ></StatusText>
      </template>
      <template #payType="{ row }">
        <StatusText
          v-if="![null, undefined].includes(row.payType)"
          class="status-text"
          :type="DICT_TYPE.SALE_PAY_TYPE"
          :value="row.payType"
        ></StatusText>
      </template>
      <template #acceptOrderTime="{ row }">
        {{ formatDate(row.acceptOrderTime) }}
      </template>
      <template #netTime="{ row }">
        {{ formatDate(row.netTime) }}
      </template>
      <template #grossTime="{ row }">
        {{ formatDate(row.grossTime) }}
      </template>
      <template #exitTime="{ row }">
        {{ formatDate(row.exitTime) }}
      </template>
      <template #auditTime="{ row }">
        {{ formatDate(row.auditTime) }}
      </template>
      <template #driverName_filter>
        <custom-form
          v-model="searchParams.driverName"
          :type="'input'"
          :maxlength="50"
          @filterChange="filterChange()"
        ></custom-form>
      </template>
      <template #driverMobile_filter>
        <custom-form
          v-model="searchParams.driverMobile"
          :type="'input'"
          :maxlength="11"
          @filterChange="filterChange()"
        ></custom-form>
      </template>
      <template #driverIdNo_filter>
        <custom-form
          v-model="searchParams.driverIdNo"
          :type="'input'"
          :maxlength="18"
          @filterChange="filterChange()"
        ></custom-form>
      </template>
      <template #planNo_filter>
        <custom-form
          v-model="searchParams.planNo"
          :type="'input'"
          :maxlength="50"
          @filterChange="filterChange()"
        ></custom-form>
      </template>
      <template #organizationName_filter>
        <custom-form
          v-model="searchParams.organizationName"
          :type="'input'"
          :maxlength="50"
          @filterChange="filterChange()"
        ></custom-form>
      </template>

      <template #operation="{ row }">
        <template v-if="visibleButtons(row).length > 0">
          <el-button
            v-for="(button, index) in visibleButtons(row)"
            :key="index"
            :type="button.type"
            :link="button.link"
            @click="
              button.action(
                row.id,
                row.customerId,
                row.tenantId
              )
            "
            v-hasPermi="button.permissions"
          >
            {{ button.label }}
          </el-button>
        </template>
      </template>
    </custom-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </section>
  <auditForm ref="auditRef" @success="getList" />
  <operatingRecordForm
    ref="operatingRecordRef"
    @success="getList"
  />
  <detail-model ref="goodsSourceDetailRef"></detail-model>
</template>
<script setup lang="ts" name="SalesManage">
import {
  listSimpleDictData,
  listSimpleJLDictData
} from '@/api/system/dict/dict.data'
import { DICT_TYPE, getJLDictOptions } from '@/utils/dict'
import { useFullscreen } from '@vueuse/core'
import * as Utils from '@/utils/dict'
import { cloneDeep } from 'lodash-es'
import operatingRecordForm from './recordDetail.vue'
import auditForm from './auditForm.vue'
import * as authorizationManageApi from '@/api/authorizationManage'
import { getTenantId } from '@/utils/auth'
import * as salesWaybillApi from '@/api/salesWaybill'
import download from '@/utils/download'
import { data } from 'autoprefixer'
import * as salesPlanApi from '@/api/salesPlan'
import DetailModel from '@/views/salesManage/salesWaybill/detailModel.vue'
const singleTableRef = ref()
const { isFullscreen, toggle } =
  useFullscreen(singleTableRef)
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const imageUrl = ref()
const dialogVisible = ref(false)
const loading = ref(false) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([])
const searchNameVal = ref('acceptOrderTime')
const timetypeList = [
  {
    value: 'acceptOrderTime',
    label: '接单时间'
  },
  {
    value: 'netTime',
    label: '轻磅时间'
  },
  {
    value: 'grossTime',
    label: '重磅时间'
  },
  {
    value: 'exitTime',
    label: '出厂时间'
  }
]

//自定义列
const columns = ref([
  {
    title: '序号',
    field: 'index',
    width: '65px',
    fixed: 'left',
    isShow: true,
    sortable: false,
    filterable: false,
    customText: true
  },
  {
    title: '所属企业',
    field: 'tenantName',
    width: '160px',
    fixed: 'left',
    isShow: true,
    sortable: false,
    filterable: true,
    customText: false
  },
  {
    title: '运单编号',
    field: 'waybillNo',
    width: '210px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: true,
    customText: true
  },
  {
    title: '客户',
    field: 'customerName',
    width: '160px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: true,
    customText: false
  },
  {
    title: '运单状态',
    field: 'waybillStatus',
    width: '150px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: true,
    customText: true
  },
  {
    title: '产品',
    field: 'productName',
    width: '150px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: true,
    customText: false
  },
  {
    title: '车牌号',
    field: 'vehicleNo',
    width: '150px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: true,
    customText: false
  },
  {
    title: '装货地',
    field: 'loadingSiteName',
    width: '150px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: true,
    customText: false
  },
  {
    title: '卸货地',
    field: 'unLoadingSiteName',
    width: '150px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: true,
    customText: false
  },
  {
    title: '皮重(吨)',
    field: 'netWeight',
    width: '120px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '毛重(吨)',
    field: 'grossWeight',
    width: '120px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '净重(吨)',
    field: 'totalWeight',
    width: '120px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '价格(元/吨)',
    field: 'endPrice',
    width: '120px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '付款账户',
    field: 'payType',
    width: '120px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: true
  },
  {
    title: '货款标记',
    field: 'goodsPaymentMark',
    width: '120px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: true
  },
  {
    title: '扣费金额(元)',
    field: 'deductionFeeAmount',
    width: '120px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '货款金额(元)',
    field: 'priceTotal',
    width: '120px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '接单时间',
    field: 'acceptOrderTime',
    width: '180px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '审核时间',
    field: 'auditTime',
    width: '180px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '轻磅时间',
    field: 'netTime',
    width: '180px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '重磅时间',
    field: 'grossTime',
    width: '180px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '出厂时间',
    field: 'exitTime',
    width: '180px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: false,
    customText: false
  },
  {
    title: '司机姓名',
    field: 'driverName',
    width: '120px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: true,
    customText: false
  },
  {
    title: '司机手机号',
    field: 'driverMobile',
    width: '120px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: true,
    customText: false
  },
  {
    title: '司机身份证号',
    field: 'driverIdNo',
    width: '180px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: true,
    customText: false
  },
  {
    title: '计划编号',
    field: 'planNo',
    width: '210px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: true,
    customText: false
  },
  {
    title: '所属组织',
    field: 'organizationName',
    width: '150px',
    fixed: null,
    isShow: true,
    sortable: false,
    filterable: true,
    customText: false
  },
  {
    title: '操作',
    field: 'operation',
    width: '200px',
    fixed: 'right',
    isShow: true,
    sortable: false,
    filterable: false,
    customText: true
  }
])
const searchParams = ref({
  tenantId: getTenantId(),
  enterId: '',
  tenantName: '',
  waybillNo: '',
  waybillStatus: '',
  productId: '',
  productName: '',
  vehicleNo: '',
  loadingPlaceId: '',
  loadingPlaceName: '',
  unloadingPlaceId: '',
  unloadingPlaceName: '',
  acceptOrderTime: '',
  netTime: '',
  grossTime: '',
  exitTime: '',
  driverName: '',
  driverMobile: '',
  driverIdNo: '',
  planNo: '',
  organizationId: '',
  organizationName: '',
  customerId: '',
  customerName: ''
})
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  dispatchTenantId: getTenantId(),
  dispatchProgramType: 2,
  segmentedDeviceCode: '0'
})
const queryFormRef = ref() // 搜索的表单
/** 列字段查询 */
const filterChange = () => {
  queryParams.value.pageNo = 1
  getList()
}

/** 所属企业列表数据 */
const tenantList = ref([])
const getOutTenantList = async () => {
  const res =
    await authorizationManageApi.getOutTenantListByIdentity(
      { identity: 1 }
    )
  tenantList.value =
    res.map((item) => ({
      value: item.id,
      label: item.enterName
    })) || []
}
const router = useRouter()
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const res = await salesWaybillApi.getSaleWaybillPage(
      getParams(queryParams.value)
    )
    if (res.code === 0) {
      total.value = res.data?.total || 0
      if (res.data.list) {
        const pageNo = Math.max(
          1,
          parseInt(queryParams.value.pageNo) || 1
        )
        const pageSize = Math.max(
          1,
          parseInt(queryParams.value.pageSize) || 10
        )

        list.value = res.data?.list.map((item, index) => ({
          ...item,
          index: (pageNo - 1) * pageSize + index + 1
        }))
      } else {
        list.value = []
      }
      getTabList(true)
      getPageTotal()
    } else if (res.code === 100910003) {
      loading.value = false
      await message.confirm(res.msg)
      refreshAuthorize()
    } else if (res.code === 100910004) {
      loading.value = false
      await message.confirm(res.msg)
      router.push({
        path: '/authManageCatalog/authorizationManage'
      })
    } else {
      message.error(res.msg)
    }
  } finally {
    loading.value = false
  }
}
const refreshAuthorize = async () => {
  await salesPlanApi.refreshAuthorize()
  queryParams.value.segmentedDeviceCode = '0'
  await setDefaultOrderPeriod()
  getOutTenantList()
  getTabList(false)
  getList()
}

/** 校验时间范围 */
const validateOrderPeriod = () => {
  // 校验时间不能为空
  if (!searchNameVal.value) {
    message.error('请选择时间类型')
    return false
  }
  if (
    !orderPeriod.value ||
    orderPeriod.value.length === 0
  ) {
    message.error('请选择时间范围')
    return false
  }
  // 校验时间范围是否超过366天
  if (orderPeriod.value && orderPeriod.value.length === 2) {
    const startDate = new Date(orderPeriod.value[0])
    const endDate = new Date(orderPeriod.value[1])

    // 计算时间差（毫秒）
    const timeDiff = endDate.getTime() - startDate.getTime()
    // 转换为天数
    const daysDiff = timeDiff / (1000 * 60 * 60 * 24)
    if (daysDiff > 366) {
      message.error('时间范围不能超过366天')
      return false
    }
    if (daysDiff < 0) {
      message.error('结束时间不能早于开始时间')
      return false
    }
  }
  return true
}
/** 搜索按钮操作 */
const handleQuery = () => {
  if (!validateOrderPeriod()) {
    return
  }
  queryParams.value.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  setDefaultOrderPeriod()
  searchNameVal.value = 'acceptOrderTime'
  if (tabs.value && tabs.value.length > 2) {
    queryParams.value.segmentedDeviceCode =
      tabs.value[2]?.value
  } else {
    queryParams.value.segmentedDeviceCode = '2'
  }
  filterWaybillStatusList(
    queryParams.value.segmentedDeviceCode
  )
  handleQuery()
}

/** 按钮操作 */
const visibleButtons = (row) => {
  const buttons = [
    {
      label: '取消',
      action: cancelFun,
      permissions: ['salesWaybill:cancel'],
      type: 'primary',
      link: true,
      visible: row.cancelBtn == 1
    },
    {
      label: '审核',
      action: auditFun,
      permissions: ['salesWaybill:audit'],
      type: 'primary',
      link: true,
      visible: row.reviewBtn == 1
    },
    {
      label: '操作记录',
      action: operatingRecordFun,
      permissions: ['salesWaybill:record'],
      type: 'primary',
      link: true,
      visible: true
    }
  ]
  return buttons.filter((btn) => btn.visible).slice(0, 3)
}

/** 取消操作 */
const cancelFun = async (id) => {
  try {
    const dataSourceValue = dataSourceList.value[1].value
    await message.confirm('您确认取消该运单吗？')
    const res = await salesWaybillApi.editWaybillStatus({
      id: id,
      status: 8,
      dataSource: dataSourceValue
    })
    if (res.code === 0) {
      message.success(t('common.operateSuccess'))
      await getList()
    } else if (res.code === 100910003) {
      await message.confirm(res.msg)
      refreshAuthorize()
    } else if (res.code === 100910004) {
      await message.confirm(res.msg)
      router.push({
        path: '/authManageCatalog/authorizationManage'
      })
    } else {
      message.error(res.msg)
    }
  } catch {}
}

/** 审核操作 */
const auditRef = ref()
const auditFun = (id, cusId, tenantId) => {
  auditRef.value.open(id, cusId, tenantId)
}

/** 操作记录操作 */
const operatingRecordRef = ref()
const operatingRecordFun = (id) => {
  operatingRecordRef.value.open(id)
}

/** 运单详情操作 */
const goodsSourceDetailRef = ref()
const openDetailModel = (id?: number) => {
  goodsSourceDetailRef.value.open(id)
}
const exportLoading = ref(false) // 导出的加载中

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await salesWaybillApi.exportData(
      getParams(queryParams.value)
    )
    download.excel(data, '销售运单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
/** 时间 */
const orderPeriod = ref([])
const setDefaultOrderPeriod = async () => {
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 2)
  orderPeriod.value = [
    startDate.toISOString().slice(0, 10) + ' 00:00:00',
    endDate.toISOString().slice(0, 10) + ' 23:59:59'
  ]
}

const getParams = (params) => {
  return { ...getTotalParams(params), ...getTimeData() }
}
const getTotalParams = (params) => {
  const data = cloneDeep(params)
  Object.keys(searchParams.value).forEach((key) => {
    if (
      ![null, undefined, ''].includes(
        searchParams.value[key]
      )
    ) {
      data[key] = searchParams.value[key]
    }
  })
  return data
}

const getTimeData = () => {
  const data = {}
  if (orderPeriod.value?.length > 1) {
    if (searchNameVal.value == 'acceptOrderTime') {
      data['acceptOrderTime'] = [
        orderPeriod.value[0],
        orderPeriod.value[1]
      ]
    }
    if (searchNameVal.value == 'netTime') {
      data['netTime'] = [
        orderPeriod.value[0],
        orderPeriod.value[1]
      ]
    }
    if (searchNameVal.value == 'grossTime') {
      data['grossTime'] = [
        orderPeriod.value[0],
        orderPeriod.value[1]
      ]
    }
    if (searchNameVal.value == 'exitTime') {
      data['exitTime'] = [
        orderPeriod.value[0],
        orderPeriod.value[1]
      ]
    }
  }
  return data
}
/** 合计 */
const getPageTotal = async () => {
  loading.value = true
  try {
    const data =
      await salesWaybillApi.getSaleWaybillPageTotal(
        getParams(queryParams.value)
      )
    resultSum.value = data || {}
  } finally {
    loading.value = false
  }
}
const resultSum = ref({})
const handleSummaries = (param) => {
  const summaries = []
  const { columns } = param
  columns.forEach((column, columnIndex) => {
    if (columnIndex === 0) {
      summaries[columnIndex] = '合计'
      return
    }
    switch (column.property) {
      case 'netWeight':
        summaries[columnIndex] =
          resultSum.value.netWeightTotal || ''
        break
      case 'grossWeight':
        summaries[columnIndex] =
          resultSum.value.grossWeightTotal || ''
        break
      case 'totalWeight':
        summaries[columnIndex] =
          resultSum.value.totalWeightTotal || ''
        break
      case 'deductionFeeAmount':
        summaries[columnIndex] =
          resultSum.value.deductionFeeAmountTotal || ''
        break
      case 'priceTotal':
        summaries[columnIndex] =
          resultSum.value.priceTotal || ''
        break
      default:
        summaries[columnIndex] = ''
    }
  })
  return summaries
}

/** 获取分段器 */
const tabs = ref([])
const activeName = ref('')
const getTabList = async (flag) => {
  const list = getJLDictOptions(
    DICT_TYPE.DISPATCH_SALE_WAYBILL_STATUS
  )
  const res =
    await salesWaybillApi.getWaybillSegmentedDevice(
      getParams(queryParams.value)
    )
  tabs.value = handleObj(list, res, flag)
}
const handleObj = (list, obj, flag) => {
  const result = list.map((e) => {
    e.num =
      (obj && typeof obj === 'object' && obj[e.label]) || 0
    return e
  })
  if (!flag) {
    queryParams.value.segmentedDeviceCode = result[2]?.value
  }
  return result
}
//切换tab查询数据
const tabChange = (tab) => {
  queryParams.value.segmentedDeviceCode = tab
  queryParams.value.pageNo = 1
  // 清空所有搜索条件
  clearSearchParams()
  filterWaybillStatusList(tab)
  getList()
}

const originalWaybillStatusList = ref([])
const filterWaybillStatusList = (segmentedDeviceCode) => {
  if (
    !originalWaybillStatusList.value ||
    originalWaybillStatusList.value.length === 0
  ) {
    return
  }
  switch (segmentedDeviceCode) {
    case '0':
      waybillstatusList.value = [
        ...originalWaybillStatusList.value
      ]
      break
    case '1':
      waybillstatusList.value =
        originalWaybillStatusList.value.filter(
          (item) => item.value === '0'
        )
      break
    case '2':
      waybillstatusList.value =
        originalWaybillStatusList.value.filter((item) =>
          ['1', '2', '3', '4', '5'].includes(item.value)
        )
      break
    case '3':
      waybillstatusList.value =
        originalWaybillStatusList.value.filter(
          (item) => item.value === '6'
        )
      break
    case '4':
      waybillstatusList.value =
        originalWaybillStatusList.value.filter((item) =>
          ['7', '8'].includes(item.value)
        )
      break
    default:
      waybillstatusList.value = [
        ...originalWaybillStatusList.value
      ]
      break
  }
}
// 清空搜索条件
const clearSearchParams = () => {
  searchParams.value = {
    tenantId: getTenantId(),
    enterId: '',
    tenantName: '',
    waybillNo: '',
    waybillStatus: '',
    productId: '',
    productName: '',
    vehicleNo: '',
    loadingPlaceId: '',
    loadingPlaceName: '',
    unloadingPlaceId: '',
    unloadingPlaceName: '',
    acceptOrderTime: '',
    netTime: '',
    grossTime: '',
    exitTime: '',
    driverName: '',
    driverMobile: '',
    driverIdNo: '',
    planNo: '',
    organizationId: '',
    organizationName: '',
    customerId: '',
    customerName: ''
  }
}

/** 自定义列 */
const customColumns = ref([])
// const getCustomColumns = async () => {
// const res = await WaybillApi.getWaybillColumns({
//   menuType: 'salesWaybillManage'
// })
// columns.value = res.fieldAttributeList || []
// customColumns.value = res.fieldAttributeList || []
// }
const getCustomColumns = () => {
  console.log('自定义列')
}
const waybillstatusList = ref([])
const dataSourceList = ref([])
const dispatchProgramTypeList = ref([])
/** 初始化 **/
onMounted(async () => {
  // await getCustomColumns()
  // customColumns.value = cloneDeep(columns.value)

  const res = await listSimpleDictData()
  waybillstatusList.value = res.filter((item) => {
    return item.dictType == 'sale_waybill_status'
  })
  const resjl = await listSimpleJLDictData()
  dataSourceList.value = resjl.filter((item) => {
    return item.dictType == 'req_system_source'
  })
  dispatchProgramTypeList.value = resjl.filter((item) => {
    return item.dictType == 'dispatch_program_type'
  })
  queryParams.value.dispatchProgramType =
    dispatchProgramTypeList.value[1].value
  originalWaybillStatusList.value = waybillstatusList.value
  await setDefaultOrderPeriod()
  getOutTenantList()
  getTabList(false)
  // await getList()   因为tab会掉list的接口，所以这里不掉list接口
})
</script>

<style lang="scss" scoped>
:deep(.el-table__header-wrapper .el-checkbox__inner) {
  display: none !important;
}

.el-table {
  :deep(.el-button) {
    height: 30px !important;
    line-height: 30px !important;
  }
}

.status-text {
  padding: 4px 0px !important;
}
</style>
